package com.example.lunbo.utils;

import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import com.example.lunbo.OnCompletionListener;
import java.io.IOException;



public class PlayerUtils {
    private static PlayerUtils instance;

    private MediaPlayer mediaPlayer;

    private PlayerUtils() {
        mediaPlayer = new MediaPlayer();
    }

    public static PlayerUtils getInstance() {
        if (instance == null) {
            synchronized (PlayerUtils.class) {
                if (instance == null) {
                    instance = new PlayerUtils();
                }
            }
        }
        return instance;
    }

    public long start(Context context, String path, OnCompletionListener callback) {
        try {
            stop();
            mediaPlayer.setDataSource(context,Uri.parse(path));
            mediaPlayer.prepare();
            mediaPlayer.start();
            mediaPlayer.setOnCompletionListener(mediaPlayer -> {
                if (callback != null) {
                    callback.onCompletion();
                }
            });

            int duration = mediaPlayer.getDuration();
            return duration;
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }
    }



    public void stop() {
        mediaPlayer.stop();
        mediaPlayer.reset();
    }
}
